package com.sugar.follow.up.module.business.controller.app.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import com.sugar.follow.up.framework.common.pojo.CommonResult;
import com.sugar.follow.up.module.business.controller.app.config.vo.AppBasicConfigRespVO;
import com.sugar.follow.up.module.business.controller.app.config.vo.MpOpenCheckSignatureReqVO;
import com.sugar.follow.up.module.business.controller.app.config.vo.MpOpenHandleMessageReqVO;
import com.sugar.follow.up.module.business.service.config.BizConfigService;
import com.sugar.follow.up.module.business.service.user.BizUserService;
import com.sugar.follow.up.module.business.util.wechat.GongZhongUtil;
import com.sugar.follow.up.module.business.util.wechat.SignUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import java.util.Objects;

import static com.sugar.follow.up.framework.common.pojo.CommonResult.successApp;

// https://suifang2025.hncykj.xyz/app-api/biz/biz-config/like
@Slf4j
@Tag(name = "APP - 参数配置")
@RestController
@RequestMapping("/biz/biz-config")
@Validated
public class AppBizConfigController {

    @Resource
    private BizConfigService bizConfigService;
    @Resource
    private BizUserService userService;

    @GetMapping("/get")
    @Operation(summary = "获得参数配置")
    @PermitAll
    public CommonResult<AppBasicConfigRespVO> getBizConfig() {
        return successApp(bizConfigService.getBizConfigBasic());
    }

    //填写和公众号后台配置的一样的token
    private static final String TOKENN = "06b67414195c4b28b05eb3cbda456163";
    private static final String ASE_KEY = "dNrCwRNcMnSHvzpMBwCVIGEWsl89LSvyIsRKKQ2I3Di";

    @GetMapping("/like")
    @Operation(summary = "校验签名")
    @PermitAll
    public String checkSignature(MpOpenCheckSignatureReqVO reqVO) {
        if (SignUtil.checkSignature(TOKENN, reqVO.getSignature(), reqVO.getTimestamp(), reqVO.getNonce())) {
            return reqVO.getEchostr();
        }

        log.error("校验不通过！");
        return "非法请求";
    }

    @PostMapping(value = "/like", produces = "application/xml; charset=UTF-8")
    @PermitAll
    public String handleMessage(@RequestBody String content, MpOpenHandleMessageReqVO reqVO) throws Exception {
        Map<String, Object> xmlMap = XmlUtil.xmlToMap(content);

        String openid = reqVO.getOpenid();
        String msgType = null;
        String event = null;

        if (StrUtil.isBlank(reqVO.getEncrypt_type())) { // 明文模式
            openid = String.valueOf(xmlMap.get("FromUserName"));
            msgType = String.valueOf(xmlMap.get("MsgType"));
            event = String.valueOf(xmlMap.get("Event"));
        } else if (Objects.equals(reqVO.getEncrypt_type(), MpOpenHandleMessageReqVO.ENCRYPT_TYPE_AES)) { // AES 加密模式
            String decrypt = decrypt(String.valueOf(xmlMap.get("Encrypt")));
            Map<String, Object> decryptMap = XmlUtil.xmlToMap(decrypt.substring(decrypt.indexOf("<xml>"), decrypt.lastIndexOf("</xml>") + 6));

            openid = String.valueOf(decryptMap.get("FromUserName"));
            msgType = String.valueOf(decryptMap.get("MsgType"));
            event = String.valueOf(decryptMap.get("Event"));
        }

        if (StrUtil.isNotBlank(openid)) {

            if ("event".equals(msgType)) {
                if (StrUtil.isNotBlank(event)) {
                    // 根据openid拿到 微信unionId （取关后获取用户信息获取不到 unionId）
                    String unionId = GongZhongUtil.getUserInfo(openid);
                    userService.updateLike(unionId, openid, "subscribe".equals(event));
                }
            }
        }

        return "";
    }

    public static String decrypt(String encryptedData) throws Exception {
        byte[] decodedData = Base64.getDecoder().decode(encryptedData);
        // 假设使用 AES 算法进行解密
        SecretKeySpec key = new SecretKeySpec(Base64.getDecoder().decode(ASE_KEY), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        // 这里通常需要 IV，假设已经取得
        IvParameterSpec iv = new IvParameterSpec(decodedData, 0, 16);
        cipher.init(Cipher.DECRYPT_MODE, key, iv);
        byte[] original = cipher.doFinal(decodedData, 16, decodedData.length - 16);
        return new String(original, StandardCharsets.UTF_8);
    }
}